from socketserver import BaseRequestHandler, TCPServer, ThreadingTCPServer, BaseServer
from threading import Thread
import zmq
import configparser
import os
import json
import time
import traceback

class DEHandler(BaseRequestHandler):
    def handle(self):
        print('socket来源IP和端口：', self.client_address)
        self.read_zip()
    
    def read_zip(self):
        try:
            config_file = 'update/tools/config.ini'
            config = configparser.ConfigParser()
            config.read(config_file)
            page_file = config.get('service_side', 'deployment_file')
            while True:
                len_num1 = self.request.recv(2)
                print(len_num1)
                if len_num1 == b'de':
                    break
                len_num2 = int(len_num1.decode('utf-8'))
                module_name = self.request.recv(len_num2)
                print(module_name)
                self.send_zip(module_name.decode('utf-8'), page_file)
                # else:
                #     module_name = self.request.recv(len_num2)
                #     print(module_name)
                #     self.send_zip(module_name.decode('utf-8'), page_file)
        except BaseException as b:  # 所有异常的基类
            print('read_zip str(e):\t\t', str(b))  # 简单
            print('read_zip repr(e):\t', repr(b))  # 较简单
            print('read_zip traceback.print_exc(): %s' % traceback.print_exc())  # 最详细
            os._exit(3)
        except:
            print('read_zip traceback.print_exc(): %s' % traceback.print_exc())  # 最详细
            os._exit(3)
        return
        
    def send_zip(self, module_name, page_file):
        try:
            page_d = os.path.join(page_file, module_name)
            with open(page_d, 'rb') as e:
                for data in e:
                    self.request.send(data)
            e.close()
            time.sleep(5)
            self.request.send(b'end')
        except BaseException as b:  # 所有异常的基类
            print('read_zip str(e):\t\t', str(b))  # 简单
            print('read_zip repr(e):\t', repr(b))  # 较简单
            print('read_zip traceback.print_exc(): %s' % traceback.print_exc())  # 最详细
            os._exit(3)
        except:
            print('read_zip traceback.print_exc(): %s' % traceback.print_exc())  # 最详细
            os._exit(3)
        return